package org.csu.mypetstore_seller.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.csu.mypetstore_seller.domain.Account;
import org.csu.mypetstore_seller.domain.AccountSign;
import org.csu.mypetstore_seller.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


import java.util.List;
import java.util.Map;

@Controller
@Slf4j
@RequestMapping("account")
public class AccountController {

    @Autowired
    AccountService accountService;

    //显示所有账户
    @GetMapping("accountMain")
    public String accountMain(Model model) {
        List<Account> accountList = accountService.getAllAccount();//拿到账户列表
        model.addAttribute("accountList", accountList);//将账户列表给网页端
        log.info("访问账户管理主页面");  // 添加日志
        return "account/account";
    }

    //点击详细信息，进行查看某个用户
    @GetMapping("profile/{userid}")//restful风格
    public String profile(@PathVariable String userid, Model model, HttpServletRequest request) {
        HttpSession session = request.getSession();
        //获取用户的账户信息
        Map<String, Object> map = accountService.getOneAccount(userid);

        //数据传给网页端
        model.addAttribute("accountToUpdate", map.get("account"));
        model.addAttribute("accountSign", map.get("accountSign"));
        session.setAttribute("accountToUpdate", map.get("account"));//存入session中，用于后续比较修改
        model.addAttribute("buttonValue", "更新个人信息");
        log.info("查看用户 {} 的详细信息", userid);  // 修改日志，添加用户ID信息
        return "account/profile";
    }

    //编辑页面点击保存
    @PostMapping("profile/{userid}")
    public String updateProfile(@PathVariable String userid,
                                @ModelAttribute Account newProfile,
                                @RequestParam(value = "username", required = false) String username,
                                @RequestParam(value = "password", required = false) String newPassword,
                                Model model,
                                HttpServletRequest request,
                                RedirectAttributes redirectAttributes) {
        log.info("开始更新用户 {} 的信息", userid);  // 添加日志
        HttpSession session = request.getSession();
        String allMsg = "";

        // 获取原始账户信息
        Map<String, Object> map = accountService.getOneAccount(userid);
        if (map == null || map.get("account") == null) {
            model.addAttribute("msg", "无法找到用户信息！");
            return "account/profile";
        }
        Account originalAccount = (Account) map.get("account");
        AccountSign originalAccountSign = (AccountSign) map.get("accountSign");

        // 更新账户信息前，先设置新账户的状态为原始状态
        newProfile.setStatus(originalAccount.getStatus());

        //检查是否由基本信息的修改
        if (!session.getAttribute("accountToUpdate").equals(newProfile)) {
            session.setAttribute("accountToUpdate", newProfile);
            allMsg += accountService.updateAccount(newProfile);
        }

        // 如果提供了新密码并且与原密码不同，则更新密码
        if (newPassword != null && !newPassword.trim().isEmpty() && !newPassword.equals(originalAccountSign.getPassword())) {
            allMsg += accountService.updatePassword(userid, newPassword);
            log.info("更新用户密码");
        }

        // 更新用户名
        if (username != null && !username.isEmpty() && !userid.equals(username)) {
            String msg = accountService.updateUsername(username, newProfile);
            if ("用户名已存在，换个名字吧！".equals(msg) || "出错啦！".equals(msg)) {
                model.addAttribute("msg", msg);
                model.addAttribute("accountToUpdate", originalAccount);
                model.addAttribute("accountSign", originalAccountSign);
                model.addAttribute("buttonValue", "更新个人信息");
                return "account/profile";
            } else {
                allMsg += " ";
                allMsg += msg;
                // 使用新的用户名作为后续操作的userid
                userid = username;  // 更新userid为新的用户名
                log.info("更新用户名");
            }
        }

        // 在更新操作完成后，使用最新的用户名（可能是更新后的）重新获取账户信息
        map = accountService.getOneAccount(userid);

        if (map == null || map.get("account") == null) {
            log.error("更新用户 {} 信息失败：无法找到用户信息", userid);  // 添加错误日志
            model.addAttribute("msg", "无法找到更新后的用户信息！");
            log.info("更新用户{}信息失败，无法找到更新后的用户信息!",userid);
            return "account/profile";
        }

        // 如果有任何更改，进行重定向以更新URL
        if (!allMsg.isEmpty()) {
            redirectAttributes.addFlashAttribute("msg", allMsg);
            redirectAttributes.addFlashAttribute("accountToUpdate", map.get("account"));
            redirectAttributes.addFlashAttribute("accountSign", map.get("accountSign"));
            redirectAttributes.addFlashAttribute("buttonValue", "更新个人信息");
            log.info("用户{}信息更新成功",userid);
            return "redirect:/account/profile/" + userid; // 重定向到更新后的userid对应的页面
        }

        // 如果没有任何更改
        if (allMsg.isEmpty()) {
            allMsg = "看起来你好像什么都没修改呢！";
        }

        // 设置模型属性
        model.addAttribute("msg", allMsg);
        model.addAttribute("accountToUpdate", map.get("account"));
        model.addAttribute("accountSign", map.get("accountSign"));
        session.setAttribute("accountToUpdate", map.get("account"));
        model.addAttribute("buttonValue", "更新个人信息");

        return "account/profile";
    }

    //删除用户
    @GetMapping("/delete/{userid}")
    public String deleteAccount(@PathVariable String userid, Model model) {
        model.addAttribute("msg", accountService.deleteAccount(userid));//进行删除
        List<Account> accountList = accountService.getAllAccount();//刷新列表
        model.addAttribute("accountList", accountList);
        log.info("删除用户 {}", userid);  // 修改日志，添加用户ID信息
        return "account/account";
    }

    //添加用户
    @GetMapping("/add")
    public String addAccount(@ModelAttribute Account accountToUpdate, @ModelAttribute AccountSign accountSign, Model model) {
        //空表对象
        model.addAttribute("accountToUpdate", accountToUpdate);
        model.addAttribute("accountSign", accountSign);
        model.addAttribute("buttonValue", "添加新用户");
        log.info("进入添加新用户页面");  // 修改日志，更具体的描述
        return "account/profile";
    }

    //提交添加新用户
    @PostMapping("/add")
    public String insertAccount(@ModelAttribute Account account,
                                @ModelAttribute AccountSign accountSign,
                                Model model,
                                RedirectAttributes redirectAttributes) {
        account.setUserid(accountSign.getUsername());
        String msg = accountService.addAccount(account, accountSign);

        if ("用户名已存在，换个名字吧！".equals(msg) || "用户名不能为空！".equals(msg)) {
            log.warn("添加用户失败：{}", msg);  // 添加警告日志
            // 用户名重复或为空的情况，保持在当前页面并显示错误信息
            model.addAttribute("msg", msg);
            model.addAttribute("accountToUpdate", account);
            model.addAttribute("accountSign", accountSign);
            model.addAttribute("buttonValue", "添加新用户");
            return "account/profile";
        } else {
            // 添加成功的消息
            redirectAttributes.addFlashAttribute("msg", msg);
            log.info("新用户 {} 添加成功", account.getUserid());  // 修改成功日志，添加用户ID
            return "redirect:/account/accountMain";
        }
    }

    //重置密码
    @GetMapping("/reset/{userid}")
    public String resetPassword(@PathVariable String userid, Model model){
        model.addAttribute("msg", accountService.resetPassword(userid));
        log.info("重置用户 {} 的密码", userid);  // 修改日志，添加用户ID信息
        return "forward:/account/accountMain";
    }
}





